package com.xwaiy.xwaiyrpc;

import com.xwaiy.xwaiyrpc.config.RegistryConfig;
import com.xwaiy.xwaiyrpc.config.RpcConfig;
import com.xwaiy.xwaiyrpc.constant.RpcConstant;
import com.xwaiy.xwaiyrpc.registry.Registry;
import com.xwaiy.xwaiyrpc.registry.RegistryFactory;
import com.xwaiy.xwaiyrpc.utils.ConfigUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * RPC 框架应用
 * 相当于 holder，存放了项目全局用到的变量。双检锁单例模式实现
 * @Author Xwaiy
 * @Date 2025/8/21 18:06
 **/
@Slf4j
public class RpcApplication {

    private static volatile RpcConfig rpcConfig;

    /**
     * 框架初始化，支持传入自定义配置
     * @param config
     */
    public static void init(RpcConfig config) {
        rpcConfig = config;
        log.info("rpc 初始化,配置为：{}", config.toString());
        // 注册中心初始化
        RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
        Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
        registry.init(registryConfig);
        log.info("注册中心初始化，配置为：{}", registryConfig);

        // ShutdownHook
        Runtime.getRuntime().addShutdownHook(new Thread(registry::destroy));
    }

    //  初始化
    public static void init(){
        RpcConfig config;
        try {
            config = ConfigUtils.loadConfig(RpcConfig.class, RpcConstant.DEFAULT_CONFIG_PREFIX);
        }catch (Exception e){
            config = new RpcConfig();
        }
        init(config);
    }

    //  获取配置
    public static RpcConfig getRpcConfig() {
        if(rpcConfig == null){
            synchronized (RpcApplication.class){
                if(rpcConfig == null){
                    init();
                }
            }
        }
        return rpcConfig;
    }
}
